package com.wwwc.admin.web.servlet;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import java.sql.SQLException;

import com.wwwc.admin.web.database.*;
import com.wwwc.util.web.*;

public class adminDatabaseManagerBean {

    public StringBuffer databaseUtils (String call_path, String database) {
	StringBuffer sbf = new StringBuffer("");
	sbf.append("<TABLE border='0'  cellSpacing='0' cellPadding='2' align=center>");
	sbf.append("<TR>");
	sbf.append("<FORM method=post action="+call_path+">");
	sbf.append("<TD><input type=submit value='Tables' style='font-size: 8pt'></TD>");
	sbf.append("<input type=hidden name=action value=list_table>");
	sbf.append("<input type=hidden name=database value="+database+">");
	sbf.append("</FORM>");
	sbf.append("<FORM method=post action="+call_path+">");
	sbf.append("<TD><input type=submit value='Query' style='font-size: 8pt'></TD>");
	sbf.append("<input type=hidden name=action value=query_form>");
	sbf.append("<input type=hidden name=database value="+database+">");
	sbf.append("</FORM>");
	sbf.append("<FORM method=post action="+call_path+">");
	sbf.append("<TD><input type=submit value='Add Table' style='font-size: 8pt'></TD>");
	sbf.append("<input type=hidden name=action value=add_table>");
	sbf.append("<input type=hidden name=database value="+database+">");
	sbf.append("</FORM>");
	sbf.append("<FORM method=post action="+call_path+">");
	sbf.append("<TD><input type=submit value='Backup' style='font-size: 8pt'></TD>");
	sbf.append("<input type=hidden name=action value=backup>");
	sbf.append("<input type=hidden name=database value="+database+">");
	sbf.append("</FORM>");
	sbf.append("</TR>");
	sbf.append("</TABLE>");
	return sbf;
    }

    public StringBuffer listDatabases(ResourceBundle config, String call_path, String database) {
	StringBuffer sbf = new StringBuffer();
	String databases = config.getString("3wcenter.databases");

	sbf.append("\n<TABLE border='0'  cellSpacing='15' cellPadding='2' align=center style='font-size: 10pt'>");

	StringTokenizer tokens = new StringTokenizer(databases, ",");
	String temp = null;
	sbf.append("<TR>");
	while (tokens.hasMoreTokens()) {
	    temp = tokens.nextToken();
	    if(database != null && database.equals(temp)) {
		sbf.append("<TD>"+temp+"</TD>");
	    }
	    else {
		sbf.append("<TD><A href="+call_path+"?database="+temp+"&action=list_table>"+temp+"</A></TD>");
	    }
	}
	sbf.append("\n</TABLE>");

	return sbf;
    }

    public StringBuffer listTable (Database db, String call_path, String database) {
	StringBuffer sbf = new StringBuffer();
	Vector rv = new Vector();
	String query = null;

	if(database.equals("Access")) {
	    query = "SELECT Name FROM MSysObjects WHERE Name Not Like 'MSys%' AND (Type=1 Or Type=6) ORDER BY Name; ";
	}
	else if(database.startsWith("Hsqldb")) {
	    query = "SELECT TABLE_NAME FROM SYSTEM_TABLES ORDER BY TABLE_NAME;";
	}
	else if(database.startsWith("MySql")) {
	    query = "SHOW TABLES;";
	}

	db.select(query);
	rv = db.getTableRecordVector();

	String temp = null;
	Enumeration enum = rv.elements();
	sbf.append("<TABLE border=1  cellSpacing=0 cellPadding=2 style='font-size: 10pt' align=center>");
	while(enum.hasMoreElements()) {
	    Enumeration enum_r = ((Vector)enum.nextElement()).elements();
	    while(enum_r.hasMoreElements()) {
		temp = (String)enum_r.nextElement();
		query = "SELECT COUNT(*) FROM "+temp+";";
		sbf.append("<TR><TD>"+temp+"</TD>");
		sbf.append("<TD>"+db.excute(query)+"</TD>");

		sbf.append("<FORM method=post action="+call_path+">");
		sbf.append("<TD><input type=submit value='View/Edit Record' style='font-size: 8pt'></TD>");
		sbf.append("<input type=hidden name=action value=view_edit_record>");
		sbf.append("<input type=hidden name=table_name value="+temp+">");
		sbf.append("<input type=hidden name=database value="+database+">");
		sbf.append("</FORM>");
		  
		sbf.append("<FORM method=post action="+call_path+">");
		sbf.append("<TD><input type=submit value='Save As' style='font-size: 8pt'></TD>");
		sbf.append("<input type=hidden name=action value=save_table_as>");
		sbf.append("<input type=hidden name=table_name value="+temp+">");
		sbf.append("<input type=hidden name=database value="+database+">");
		sbf.append("</FORM>");
			
		sbf.append("<FORM method=post action="+call_path+">");
		sbf.append("<TD><input type=submit value='Load Data' style='font-size: 8pt'></TD>");
		sbf.append("<input type=hidden name=action value='load_data_from_file'>");
		sbf.append("<input type=hidden name=table_name value="+temp+">");
		sbf.append("<input type=hidden name=database value="+database+">");
		sbf.append("</FORM>");
			
		sbf.append("<FORM method=post action="+call_path+">");
		sbf.append("<TD><input type=submit value='Drop Table' style='font-size: 8pt'></TD>");
		sbf.append("<input type=hidden name=action value=drop_table>");
		sbf.append("<input type=hidden name=table_name value="+temp+">");
		sbf.append("<input type=hidden name=database value="+database+">");
		sbf.append("</FORM>");

		sbf.append("<FORM method='post' action='"+call_path+"'>");
		sbf.append("<TD><input type=submit value='Table Info' style='font-size: 8pt'></TD>");
		sbf.append("<input type=hidden name=action value=table_info>");
		sbf.append("<input type=hidden name=table_name value="+temp+">");
		sbf.append("<input type=hidden name=database value="+database+">");
		sbf.append("</FORM>");
		sbf.append("</TR>");
	    }
	}
	sbf.append("</TABLE>");
	return sbf;
    }

    public StringBuffer deleteTable (HttpServletRequest request, String call_path, 
				     Database db, String database, String table_name) {
	String error = null;
	String submit = request.getParameter("B");
	if(submit != null) {
	    if(submit.equals("Drop Table")) {
		error = db.deleteTable(table_name);
		//error = db.removeTable(table_name);
	    }
	    if(error == null) {
		return listTable (db, call_path, database);
	    }
	}

	StringBuffer sbf = new StringBuffer();
	sbf.append("<FORM method='post' action='"+call_path+"'>");
	sbf.append("<TABLE align=center>");
	sbf.append("<TR>");	
	sbf.append("<TD colspan=2 align=center><H2> Worning ! Drop Table ["+table_name+"]</H2></TD>");
	sbf.append("</TR>");

	if(error != null) {
	    sbf.append("<TR><TD colspan=2 align=center><I><img src=/images/star.gif>"+error+"</I></TD></TR>");
	}	

	sbf.append("<TR>");	
	sbf.append("<TD><input type=submit name='B' value='Drop Table' style='font-size: 8pt'></TD>");
	sbf.append("<TD><input type=submit name='B' value='Cancle' style='font-size: 8pt'></TD>");
	sbf.append("</TR>");
	sbf.append("</TABLE>");
	sbf.append("<input type=hidden name=action value=drop_table>");
	sbf.append("<input type=hidden name=table_name value="+table_name+">");
	sbf.append("<input type=hidden name=database value="+database+">");
	sbf.append("</FORM>");
	return sbf;
    }
 
    public StringBuffer viewEditRecord(HttpServletRequest request, String call_path, String table_name, 
				       Database db, String database, String page, String max_rows) {
	StringBuffer error = null;
	HttpSession session = request.getSession(true);
	String action = request.getParameter("action");
	StringBuffer sbf = new StringBuffer();
	String submit = request.getParameter("B");
	
	Vector vro    = null;
	Vector vrd    = null;
	String row_id = null;

	if(submit != null) {
	    vrd = new Vector();
	    Vector vch = (Vector)session.getAttribute("ColumnHead");
	    Enumeration enum = vch.elements();
	    while(enum.hasMoreElements()) {
		vrd.add(request.getParameter((String)enum.nextElement()));
	    }

	    Vector old_vrs = null;
	    
	    if(!submit.equals("Add Record")) {
		row_id = request.getParameter("row_id");
		old_vrs = (Vector)session.getAttribute("Records");
		vro = (Vector)old_vrs.elementAt(Integer.parseInt(row_id));
	    }

	    if(submit.equals("Update")) {
		Vector vrs = new Vector();
		Vector vrh = new Vector();
		String temph = null;
		String tempv = null;

		enum = vch.elements();
		while(enum.hasMoreElements()) {
		    temph = (String)enum.nextElement();
		    tempv = request.getParameter(temph);
		    if(tempv != null && tempv.length()>0) {
			vrs.add(tempv);
			vrh.add(temph);
		    }
		}

		error = db.update(table_name, vro, vrh, vrs);

		if(error == null) {
		    vrd = null;
		    vro = null;
		}
	    }

	    if(submit.equals("Add Record")) {
		Vector vrs = new Vector();
		Vector vrh = new Vector();
		enum = vch.elements();
		String temph = null;
		String tempv = null;
		while(enum.hasMoreElements()) {
		    temph = (String)enum.nextElement();
		    tempv = request.getParameter(temph);
		    if(tempv != null && tempv.length()>0) {
			vrs.add(tempv);
			vrh.add(temph);
		    }
		}

		error = db.insert(table_name, vrh, vrs);

		if(error == null) {
		    vrd = null;
		    vro = null;
		}
	    }

	    if(submit.equals("Delete")) {
		error = db.delete(table_name, vro);
		vrd = null;
		//vro = null;
	    }

	    if(submit.equals("Reset")) {
		error = null;
		vrd = null;
		vro = null;
	    }
	}
	
	Vector rh = new Vector();
	Vector rt = new Vector();
	Vector rv = new Vector();
	Vector rs = new Vector();
	int row_counter = db.getRowCounter(table_name);
	String query = null;

	if(database.equals("Access")) {
	    max_rows = ""+row_counter;
	    query = "SELECT * FROM "+table_name+";";
	}

	if(database.startsWith("Hsql")) {
	    if(table_name.equals("MAIN_MENU") || table_name.equals("MENU")) {
		query = "SELECT LIMIT "+(Integer.parseInt(page)-1)*Integer.parseInt(max_rows)+
		    " "+max_rows+" * FROM "+table_name +" ORDER BY SID;";
	    }
	    else {
		query = "SELECT LIMIT "+(Integer.parseInt(page)-1)*Integer.parseInt(max_rows)+" "+max_rows+" * FROM "+table_name +";";
	    }
	}
	 

	if(database.startsWith("MySql")) {
	    query = "SELECT * FROM "+table_name +";";
	}

	db.select(query, table_name, database);
	Vector prim_keys_v = db.getTablePrimaryKeysVector();
	rt = db.getTableColumnTypeVector();
	rs = db.getTableColumnSizeVector();
	rh = db.getTableColumnNameVector();
	rv = db.getTableRecordVector();

	session.setAttribute("ColumnHead", rh);
	session.setAttribute("Records", rv);

	if(row_id != null && vro != null) {
	    row_id = ""+rv.indexOf(vro);
	}

	Enumeration enum  = null;
	Enumeration enumh = null;
	Enumeration enumt = null;
	int cln = rt.size();
	String temp  = null;
	String temph = null;
	String tempt = null;

	sbf.append("<TABLE border=1 cellSpacing=0 cellPadding=0 style='font-size: 8pt' width=100%>");
	sbf.append("<TR>");
	sbf.append("<TD style='font-size: 12pt' align=center border=0>Database</TD>");
	sbf.append("<TD style='font-size: 16pt' align=center border=0>"+database.toUpperCase()+"</TD>");
	sbf.append("<TD style='font-size: 12pt' align=center border=0>Table</TD>");
	sbf.append("<TD style='font-size: 16pt' align=center border=0>"+table_name+"</TD>");
	sbf.append("</TR>");

	if(error != null) {
	    sbf.append("<TR>");
	    sbf.append("<TD colspan='4' align='center'><img src='/images/star.gif'><B><I>"+submit+" Error!</I></B></TD>");
	    sbf.append("</TR>");
	    sbf.append("<TR>");
	    sbf.append("<TD colspan='4' align='center'>");
	    sbf.append("<FORM>");
	    sbf.append("<TEXTAREA name=query rows=5 cols=74>"+error+"</TEXTAREA>");
	    sbf.append("</FORM>");
	    sbf.append("</TD></TR>");
	}
	sbf.append("</TABLE>");
	    
	String page_call_back = call_path+"?action=view_edit_record&database="+database+"&table_name="+table_name+"&mid=2";
	sbf.append(MyHtml.pageCounter(row_counter, max_rows, page, page_call_back));
	    
	sbf.append("<TABLE border=1 cellSpacing=0 cellPadding=0 width='100%'>");
	sbf.append("<TR><TD>-</TD><TD>-</TD><TD>-</TD>");

	enumh = rh.elements();
	while (enumh.hasMoreElements()) {
	    temph = (String)enumh.nextElement();
	    if(prim_keys_v.contains(temph)) {
		sbf.append("<TD style='font-size: 6pt'>"+temph+"(*)</TD>");
	    }
	    else {
		sbf.append("<TD style='font-size: 6pt'>"+temph+"</TD>");
	    }
	}

	sbf.append("<TD>-</TD><TD>-</TD><TD>-</TD></TR>");
	
	sbf.append("<TR><TD>-</TD><TD>-</TD><TD>-</TD>");	    
	enumt = rt.elements();

	while (enumt.hasMoreElements()) {
	    tempt = (String)enumt.nextElement();
	    if(tempt.equals("VARCHAR_IGNORECASE")) {
		tempt="VARN";
	    }
	    if(tempt.equals("INTEGER")) {
		tempt="INT";
	    }
	    if(tempt.equals("VARCHAR")) {
		tempt="VAR";
	    }
	    if(tempt.equals("TIMESTAMP")) {
		tempt="TSP";
	    }
	    sbf.append("<TD style='font-size: 6pt'>"+tempt+"</TD>");
	}

	sbf.append("<TD>-</TD><TD>-</TD><TD>-</TD></TR>");
	    
	//===============================================
	// Data records
	//===============================================

	enum = rv.elements();
	int font = 6;
	if(rh.size()<10) {
	    font =8;
	}

	if(rh.size()>10 && rh.size()<15) {
	    font =6;
	}

	StringBuffer rsbf = null;
	int n   = 0;
	int row = 0;

	while (enum.hasMoreElements()) {
	    Enumeration enum1 = ((Vector)enum.nextElement()).elements();
	    n = 0;
	    rsbf = new StringBuffer("");
	    rsbf.append("<TD>["+row+"]</TD>");
	    while (enum1.hasMoreElements()) {
		temp  = (String)enum1.nextElement();
		if(temp==null) {
		    temp = "";
		}
		
		rsbf.append("<TD align=left>");
		rsbf.append("<input type=text name="+rh.elementAt(n)+" size='"+(rh.elementAt(n)+"").length()+"' ");
		if(temp.indexOf("\"") !=-1) {
		    temp = temp.replaceAll("\"","&quot;");
		}
		if(temp.indexOf(">") !=-1) {
		    temp = temp.replaceAll(">","&gt;");
		}
		if(temp.indexOf("<") !=-1) {
		    temp = temp.replaceAll("<","&lt;");
		}
		rsbf.append(" value=\""+temp+"\" style='font-size: "+font+"pt; border=0'></TD>");  		
		n++;
	    }
	    rsbf.append("<TD>["+row+"]</TD>");

	    sbf.append("<FORM method='post' action='"+call_path+"'>");
	    sbf.append("<TR>");
	    sbf.append("<TD>");
	    sbf.append("<input type=submit name=B value=Edit  style='font-size: 6pt'>");
	    sbf.append("</TD>");
	    sbf.append("<TD>");
	    sbf.append("<input type=submit name='B' value=Delete style='font-size: 6pt'>");
	    sbf.append("</TD>");
	    sbf.append(rsbf);
	    sbf.append("<TD>");
	    sbf.append("<input type=submit name=B value=Edit  style='font-size: 6pt'>");
	    sbf.append("</TD>");
	    sbf.append("<TD>");
	    sbf.append("<input type=submit name='B' value=Delete style='font-size: 6pt'>");
	    sbf.append("</TD>");
	    sbf.append("</TR>");
	    sbf.append("<input type=hidden name=action value="+action+">");
	    sbf.append("<input type=hidden name=table_name value="+table_name+">");
	    sbf.append("<input type=hidden name=database value="+database+">");
	    sbf.append("<input type=hidden name=pid value="+page+">");
	    sbf.append("<input type=hidden name=row_id value="+row+">");
	    sbf.append("</FORM>");
	    row++;
	}
	sbf.append("</TABLE>");

	//===============================================================
	// add new or update record
	//===============================================================
	
	if(vrd != null) {
	    sbf.append("<FORM method=post action="+call_path+">");
	    sbf.append("<TABLE border=1 style='font-size: 8pt' width=100%>");
	    sbf.append("<TR><TD><B>NAME</B></TD><TD><B>TYPE</B></TD><TD><B>VALUE</B></TD></TR>");
	
	    enum = rh.elements();
	    n=0;
	   
	    String old_value = null;
	    while(enum.hasMoreElements()) {
		temp = (String)enum.nextElement();
		if(prim_keys_v.contains(temp)) {
		    sbf.append("<TR><TD>*"+temp+"</TD>");
		}
		else {
		    sbf.append("<TR><TD>&nbsp;"+temp+"</TD>");
		}
		sbf.append("<TD>"+rt.elementAt(n)+"</TD>");
	    
		old_value = (String)vrd.elementAt(n);

		if(old_value==null) {
		    old_value ="";
		}

		if(old_value.indexOf("\"") != -1) {
		    old_value = old_value.replaceAll("\"","&qute");
		}

		sbf.append("<TD><input type=text name="+temp+" value=\""+old_value+"\" size='100'></TD></TR>");
		n++;
	    }

	    sbf.append("</TABLE>");

	    if(submit.equals("Edit") || submit.equals("Update")) {
		sbf.append("<BR><input type=submit name='B' value='Update'  style='font-size: 8pt'>");
		sbf.append("<input type=submit name='B' value='Reset'  style='font-size: 8pt'>");
		sbf.append("<input type=submit name='B' value='Add Record'  style='font-size: 8pt'>");
	    }

	    if(submit.equals("Add Record")) {
		sbf.append("<BR><input type=submit name='B' value='Add Record'  style='font-size: 8pt'>");
		sbf.append("<input type=submit  name='B' value='Reset'  style='font-size: 8pt'>");
	    }

	    sbf.append("<input type=hidden name=action value=view_edit_record>");
	    sbf.append("<input type=hidden name=database value="+database+">");
	    sbf.append("<input type=hidden name=pid value="+page+">");
	    sbf.append("<input type=hidden name=table_name value="+table_name+">");
	    sbf.append("<input type=hidden name=mid value=2>");
	    sbf.append("<input type=hidden name=row_id value="+row_id+">");
	    sbf.append("</FORM>");
	}
	else {	
	    sbf.append("<FORM method=post action="+call_path+">");
	    sbf.append("<TABLE border=1 style='font-size: 8pt' width=100%>");
	    sbf.append("<TR><TD><B>NAME</B></TD><TD><B>TYPE</B></TD><TD><B>VALUE</B></TD></TR>");
	
	    enum = rh.elements();
	    n=0;

	    while(enum.hasMoreElements()) {
		temp = (String)enum.nextElement();
		if(prim_keys_v.contains(temp)) {
		    sbf.append("<TR><TD>*"+temp+"</TD>");
		}
		else {
		    sbf.append("<TR><TD>&nbsp;"+temp+"</TD>");
		}
		sbf.append("<TD>"+rt.elementAt(n)+"</TD>");
		sbf.append("<TD><input type=text name="+temp+" value='' size='100'></TD></TR>");
		n++;
	    }

	    sbf.append("</TABLE>");
	    sbf.append("<BR><input type=submit name='B' value='Add Record'  style='font-size: 8pt'>");
	    sbf.append("<input type=hidden name=action value=view_edit_record>");
	    sbf.append("<input type=hidden name=database value="+database+">");
	    sbf.append("<input type=hidden name=pid value="+page+">");
	    sbf.append("<input type=hidden name=table_name value="+table_name+">");
	    sbf.append("<input type=hidden name=mid value=2>");
	    sbf.append("</FORM>");
	}
	return sbf;
    }

    public  StringBuffer getTableInfo(Database db, String table_name, boolean show_driver_info) {
	StringBuffer sbf = new StringBuffer();
	try {
	    db.setTableInfo(table_name);
	    Vector pkv = db.getTablePrimaryKeysV(table_name);
	    Vector rt  = db.getTableColumnTypeVector();
	    Vector rs  = db.getTableColumnSizeVector();
	    Vector rh  = db.getTableColumnNameVector();
	    int row_counter = db.getRowCounter(table_name);
	    String database = db.getDataBaseName();

	    if(rt == null || rs == null || rh == null) {
		System.out.println("Database Error:adminDatabaseManagerBean:getTableInfo:103");
		return null;
	    }

	    if(rt.size() != rs.size() || rt.size() != rh.size()) {
		sbf.append("<BR> rt.size="+rt.size());
		sbf.append("<BR> rs.size="+rs.size());
		sbf.append("<BR> rh.size="+rh.size());
		return sbf;
	    }

	    Enumeration enums = null;
	    Enumeration enumh = null;
	    Enumeration enumt = null;

	    String temps = null;
	    String temph = null;
	    String tempt = null;

	    sbf.append("<TABLE border='1' cellSpacing='0' cellPadding='2' align=center>");
	    if(show_driver_info) {
		sbf.append("<TR>");
		sbf.append("<TD><B>Database</B></TD>");
		sbf.append("<TD>"+database.toUpperCase()+"</TD>");
		sbf.append("</TR>");
	    }

	    sbf.append("<TR>");
	    sbf.append("<TD><B>Table Name</B></TD>");
	    sbf.append("<TD>"+table_name+"</TD>");
	    sbf.append("</TR>");
	    sbf.append("<TR>");
	    sbf.append("<TD><B>Records</B></TD>");
	    sbf.append("<TD>"+row_counter+"</TD>");
	    sbf.append("</TR>");
	    sbf.append("</TABLE>");

	    //================================================================
	    // column names
	    //================================================================
	    sbf.append("<BR>");
	    sbf.append("<TABLE border='1' cellSpacing='0' cellPadding='2'>");
	    sbf.append("<TR>");
	    sbf.append("<TD><B>Column Name</B></TD>");
	    sbf.append("<TD><B>Data Type</B></TD>");
	    sbf.append("<TD><B>Column Size</B></TD>");
	    sbf.append("</TR>");

	    enumh = rh.elements();
	    enumt = rt.elements();
	    enums = rs.elements();

	    while (enumh.hasMoreElements()) {
		sbf.append("<TR>");
		temph = (String)enumh.nextElement();
		if(pkv != null && pkv.contains(temph)) {
		    sbf.append("<TD>"+temph+"(*)</TD>");
		}
		else {
		    sbf.append("<TD>"+temph+"</TD>");
		}
		
		tempt = (String)enumt.nextElement();
		sbf.append("<TD>"+tempt+"</TD>");
		
		temps = (String)enums.nextElement();
		sbf.append("<TD>"+temps+"</TD>");
		sbf.append("</TR>");
	    }

	    sbf.append("</TABLE>");
	}
	catch (Exception e) {
	    System.out.println("adminDatabaseManagerBean:getTableInfo:Error:"+e);
	}
	return sbf;
    }

    public StringBuffer loadDataFromFile(HttpServletRequest request, String backup_home) {
	String call_path  = request.getServletPath();
	String database   = request.getParameter("database");
	String table_name = request.getParameter("table_name");
	
	StringBuffer sbf = new StringBuffer();
	if(database == null || table_name == null || backup_home == null) {
	    sbf.append("adminDatabaseManagerBean:Error:101");
	    return sbf;
	}

	File f = new File(backup_home+"/"+ database);
	if (!f.isDirectory()){
	    return sbf.append("adminDatabaseManagerBean:Error:102");
	}

	sbf.append("<CENTER>");
	sbf.append("\n<Form method='post' action='"+call_path+"'>");
	sbf.append("\n<TABLE cellSpacing=0 cellPadding=0 border=1 width='90%'>");
	sbf.append("<TR><TD colspan='2' style='font-size: 12pt' align='center'>Please select your data file</TD></TR>");
	sbf.append("<TR><TD colspan='2' style='font-size: 10pt' align='center'>Table Name["+table_name+"]</TD></TR>");
	sbf.append("<TR><TD colspan='2' style='font-size: 10pt' align='center'>Databse["+database+"]</TD></TR>");

	File fs[] = f.listFiles(); 
	String fname = null;
	for(int n=0; n<fs.length;n++) {
	    if(fs[n].isFile()) {
		fname = fs[n].getPath();
		sbf.append("<TR><TD>"+fname+"</TD>");
		sbf.append("<TD><input type='radio' name='fname' value='"+fname+"'></TD>");
		sbf.append("</TR>");
	    }
	}
	sbf.append("<TR><TD colspan='2' align='center'><input type='submit' value='Load' style='font-size:8pt'></TD></TR>");
	sbf.append("\n</TABLE>");
	sbf.append("\n</FORM>");
	sbf.append("</CENTER>");
	return sbf;
    }

    public StringBuffer addTable(HttpServletRequest request, Database db, String call_path, String database, String databases) {
	StringBuffer error = null;
	StringBuffer sbf = new StringBuffer();
	String table_name = null;
	String add_step = request.getParameter("add_step");
		
	if(add_step == null) {
	    sbf.append("<CENTER>");
	    sbf.append("<H1>Generate Table in "+database+"</H1>");
	    sbf.append("<FORM method=post action="+call_path+">");
	    sbf.append("<TABLE border=1 style='font-size: 10pt'  cellSpacing=0 cellPadding=2>");
	    sbf.append("<TR><TD>Table Name</TD>");
	    sbf.append("<TD><input type=text name=table_name style='font-size: 8pt'></TD></TR>");
	    sbf.append("<TR><TD>Total Fields</TD><TD><input type=text name=n_fields value=30 size=3></TD></TR>");
	    sbf.append("</TABLE>");
	    sbf.append("<input type=hidden name=database value="+database+">");
	    sbf.append("<input type=hidden name=add_step value=step2>");
	    sbf.append("<input type=hidden name=action value='add_table'>");
	    sbf.append("<BR><BR><input type=submit name=B value='Next' style='font-size: 8pt'>");
	    sbf.append("</FORM>");
	    sbf.append("</CENTER>");
	    return sbf;
	}
	else if(add_step.equals("step2")){
	    table_name = request.getParameter("table_name");
	    StringBuffer type_bf = new StringBuffer();
		
	    if(database.startsWith("Hsqldb")) {
		//DOUBLE [PRECISION] | FLAT as Java type "double" | "java.lang.Double" 
		//VARCHAR Integer.MAXVALUE "java.lang.String" 
		//VARCHAR_IGNORECASE Integer.MAXVALUE "java.lang.String" 
		//CHAR | CHARACTER Integer.MAXVALUE "java.lang.String" 
		//LONGVARCHAR Integer.MAXVALUE "java.lang.String" 
		//DATE as Java type "java.sql.Date" 
		//TIME as Java type "java.sql.Time" 
		//TIMESTAMP | DATETIME as Java type "java.sql.Timestamp" 
		//DECIMAL No limit "java.math.BigDecimal" 
		//NUMERIC No limit "java.math.BigDecimal" 
		//BIT as Java type "boolean" | "java.lang.Boolean" 
		//TINYINT as Java type "byte" | "java.lang.Byte" 
		//SMALLINT as Java type "short" | "java.lang.Short" 
		//BIGINT as Java type "long" | "java.lang.Long" 
		//REAL as Java type "double" | "java.lang.Double"  
		//BINARY Integer.MAXVALUE "byte[]" 
		//VARBINARY Integer.MAXVALUE "byte[]" 
		//LONGVARBINARY Integer.MAXVALUE "byte[]" 
		//OTHER | OBJECT Integer.MAXVALUE "java.lang.Object" 
		type_bf.append("<option value=VARCHAR>VARCHAR</option>");
		type_bf.append("<option value=VARCHAR_IGNORECASE>VARCHAR_IGNORECASE</option>");
		type_bf.append("<option value=INTEGER>INTEGER</option>");
		type_bf.append("<option value=DOUBLE>DOUBLE[PRECISION]</option>");
		type_bf.append("<option value=FLOAT>FLOAT</option>");
		type_bf.append("<option value=CHAR>CHARACTER</option>");
		type_bf.append("<option value=DATE>DATE</option>");
		type_bf.append("<option value=TIME>TIME</option>");
		type_bf.append("<option value=TIMESTAMP>TIMESTAMP</option>");
		type_bf.append("<option value=DECIMAL>DECIMAL</option>");
		type_bf.append("<option value=NUMERIC>NUMERIC</option>");
		type_bf.append("<option value=BIT>BOOLEAN</option>");
		type_bf.append("<option value=BIGINT>LONG</option>");
		type_bf.append("<option value=BINARY>BINARY</option>");
		type_bf.append("<option value=OTHER>OBJECT</option>");
	    }
	    else if(database.equals("Access") || database.startsWith("MySql")) {
		type_bf.append("<option value=VARCHAR>VARCHAR</option>");
		type_bf.append("<option value=INTEGER>INTEGER</option>");
		type_bf.append("<option value=DOUBLE>DOUBLE</option>");
		type_bf.append("<option value=CHAR>CHARACTER</option>");
		type_bf.append("<option value=DATE>DATE</option>");
		type_bf.append("<option value=TIME>TIME</option>");
		type_bf.append("<option value=TIMESTAMP>TIMESTAMP</option>");
		type_bf.append("<option value=DECIMAL>DECIMAL</option>");
		type_bf.append("<option value=NUMERIC>NUMERIC</option>");
		type_bf.append("<option value=BIT>BOOLEAN</option>");
		type_bf.append("<option value=BIGINT>LONG</option>");
		type_bf.append("<option value=BINARY>BINARY</option>");
		type_bf.append("<option value=OTHER>OBJECT</option>");
	    }
	    else {
		sbf.append("Please add Data type in adminDatabaseManager");
		return sbf;
	    }

	    String n_fields   = request.getParameter("n_fields");
	    sbf.append("<CENTER>");
	    sbf.append("<H1>Create Table [ "+table_name+" ] in Databse [ "+database+"]</H1>");
	    sbf.append("<FORM name=tf method=post action="+call_path+">");
	    sbf.append("<TABLE border=1 width=100% style='font-size: 10pt'  cellSpacing=0 cellPadding=2>");
	    sbf.append("<TR><TD>&nbsp;</TD><TD>NAME</TD><TD>TYPE</TD><TD>SIZE</TD><TD>DEFAULT VALUE</TD>");
	    sbf.append("<TD>REQUIRED</TD>");

	    if(database.startsWith("Hsqldb")) {
		sbf.append("<TD><input type=radio name=identity checked value='-1'>");
		sbf.append("IDENTITY</A></TD>");
	    }
	    sbf.append("<TD>PRIMARY KEY</TD></TR>");
		
	    for (int n=1; n <= Integer.parseInt(n_fields);n++) {
		sbf.append("<TR>");
		sbf.append("<TD><input type=radio name=last_field value="+n+" style='font-size: 8pt'></TD>");
		sbf.append("<TD><input type=text name=field_"+n+" value=FIELD"+n+" style='font-size: 8pt'></TD>");
		sbf.append("<TD><select name=type_"+n+" style='font-size: 8pt'>");
		sbf.append(type_bf.toString()+"</select></TD>");

		sbf.append("<TD><input type=text name=size_"+n+" value=100 style='font-size: 8pt'></TD>");
		sbf.append("<TD><input type=text name=default_value_"+n+" style='font-size: 8pt'></TD>");
		sbf.append("<TD><select name=required_"+n+" style='font-size: 8pt'>");
		sbf.append("<option value='NULL'>No</option>");
		sbf.append("<option value='NOT NULL'>Yes</option>");
		sbf.append("</select></TD>");

		if(database.startsWith("Hsqldb")) {
		    sbf.append("<TD><input type=radio name=identity value="+n+">");
		    sbf.append("IDENTITY</TD>");
		}
		sbf.append("<TD><input type=checkbox name=primary_key_"+n+" value="+n+">PRIMARY KEY</TD>");
		sbf.append("</TR>");
	    }

	    sbf.append("</TABLE>");

	    sbf.append("<TABLE border=1 width=100% style='font-size: 10pt' cellSpacing=0 cellPadding=2>");
	    String temp = null;
	    StringTokenizer tokens = new StringTokenizer(databases, ",");
	    sbf.append("<TR>");
	    while (tokens.hasMoreTokens()) {
		temp = tokens.nextToken();
		if(!temp.equals(database)) {
		    sbf.append("<TD align=center><input type=checkbox name="+temp+" value=Yes>&nbsp;"+temp+"</TD>");
		}
	    }
	    sbf.append("</TR>");
	    sbf.append("</TABLE>");

	    sbf.append("<input type=hidden name=database value="+database+">");
	    sbf.append("<input type=hidden name=table_name value="+table_name+">");
	    sbf.append("<input type=hidden name=n_fields value="+n_fields+">");
	    sbf.append("<input type=hidden name=add_step value=step3>");
	    sbf.append("<input type=hidden name=action value='add_table'>");
	    sbf.append("<BR><BR><input type=submit value='Next' style='font-size: 8pt'>");
	    sbf.append("<input type=reset value='Reset' style='font-size: 8pt'>");
	    sbf.append("</FORM>");
	    sbf.append("</CENTER>");
	    return sbf;
	}
	else if(add_step.equals("step3")){
	    sbf.append(excuteAddTable(request, database));
	    String temp = null;
	    String selected_database = null;
	    StringTokenizer tokens = new StringTokenizer(databases, ",");
	    while (tokens.hasMoreTokens()) {
		temp = tokens.nextToken();
		selected_database = request.getParameter(temp);
		if(selected_database != null && selected_database.equals("Yes")) {
		    sbf.append("<BR>"+excuteAddTable(request, temp));
		}
	    }
	}
	return sbf;
    }

    private String excuteAddTable(HttpServletRequest request, String database) {
	HttpSession session = request.getSession();
	ResourceBundle config = (ResourceBundle)session.getAttribute("Configuration");
	Database db = DatabaseAdapter.getDatabase(database, config);
	String table_name = request.getParameter("table_name");
	StringBuffer fqbf = new StringBuffer("");
	if(database.equals("Access") || database.startsWith("MySql")) {
	    fqbf.append("CREATE TABLE "+ table_name+"(");
	} 
	else if(database.startsWith("Hsqldb")) {
	    fqbf.append("CREATE CACHED TABLE "+ table_name+"("); 
	}
	else {
	    return "adminDatabaseManagerBean:excuteAddTable:Error[database type:"+database+"]";
	}

	StringBuffer qbf = new StringBuffer("");

	String name = null;
	String type = null;

	String n_fields  = request.getParameter("last_field");
	String id  = request.getParameter("identity");
	String key = request.getParameter("primary_key");

	String keys = "";

	if(n_fields != null) {
	    for(int i=1; i<=Integer.parseInt(n_fields); i++) {
		name = request.getParameter("field_"+i)+" ";
		qbf.append(name);
		type = request.getParameter("type_"+i);
		qbf.append(type);

		if(type.equals("VARCHAR")||type.equals("INTEGER")||
		   type.equals("DOUBLE")||type.equals("CHAR")||type.equals("BIGINT")) {
		    qbf.append("(");
		    qbf.append(request.getParameter("size_"+i)+")");
		}

		qbf.append(" "+request.getParameter("default_value_"+i)+" ");
		qbf.append(request.getParameter("required_"+i)+" ");
		
		if(id != null && id.equals(i+"")){
		    qbf.append("IDENTITY ");
		}

		if(id.equals("-1")) {
		    key = request.getParameter("primary_key_"+i);
		    if(key != null && key.equals(i+"")){
			if(keys.length()>1) {
			    keys = keys +","+ name;
			}
			else {
			    keys = name;
			}
		    }
		}
		
		if(i != Integer.parseInt(n_fields)) {
		    qbf.append(",");
		}
	    }
		
	    if(keys.length()>=1) {
		fqbf.append(qbf+", PRIMARY KEY ("+keys+"));");
	    }
	    else {
		fqbf.append(qbf+");");
	    }
	    int result = -1;
	    
	    try{
		result = db.createTable(fqbf.toString());
	    }
	    catch(Exception e) {
		System.out.println("adminDatabaseManagerBean:excuteAddTable:Error:"+fqbf.toString()+"<BR>"+e);
	    }

	    if(result == -1) {
		return "<BR>Error Adding Table ["+table_name+"]<BR> database=["+database+"]"+
		    "<BR>result=["+result+"]<BR>query=["+fqbf+"]<BR>Message["+db.getMessage()+"]";
	    }
	    else {
		return "TABLE ["+table_name+"] has been crated in database ["+database+"].";
	    }
	}
	return "Ok";
    }

    public StringBuffer backup (HttpServletRequest request, Database db, String call_path, String backup_home, 
				String database, String source_dir) {
	StringBuffer sbf = new StringBuffer();
	File f = new File(backup_home+"/"+database+"/data/hypersonic/"+MyDateAndTime.getCurrentDate(3));
	if(!f.isDirectory()) {
	    f.mkdirs();
	}
	else {
	    sbf.append("Backup of "+MyDateAndTime.getCurrentDate(3)+" exists.");
	    return sbf;
	}

	File fs = new File(source_dir);
	if(!fs.isDirectory()) {
	    sbf.append("Source dir "+source_dir+" not found!");
	}

	MyCopyFile cf = new MyCopyFile();
	File fb[] = fs.listFiles();
	String error = null;
	int m =0;
	for(int n=0; n<fb.length;n++) {
	    if(fb[n].isFile()) {
		error = cf.setFiles(new File(fb[n].getPath()), new File(f.getPath()+"/"+fb[n].getName()));
		if(error == null) {
		    error = cf.copy();
		    if(error != null) {
			break;
		    }
		    else {
			m++;
		    }
		}
		else {
		    break;
		}
	    }
	}

	if(error == null) {
	    sbf.append("Backup for "+MyDateAndTime.getCurrentDate(3)+" ............. down!");
	}
	else {
	    if(m>0) {
		for(int j=0; j<m; j++) {
		    (new File (fs.getPath()+"/"+fb[j].getName())).delete();
		}
	    }
	    sbf.append(error);
	}
	return sbf;
    }
}
